import asyncio
import logging
import sys

from dependency_injector.wiring import Provide, inject

from fastapi_template.containers import DI
from fastapi_template.custom_logging import setup_logging
from fastapi_template.models import init_models


@inject
async def background_job(
        # task_facade: TaskFacade = Provide[DI.task_facade],
):
    try:
        # await task_facade.handle_background_job()
        logging.info("background_job done")
        pass
    except Exception:
        logging.exception("background_job error:")


async def main():
    setup_logging(json_logs=True, log_level="INFO")
    await init_models()
    container = DI()
    container.wire(modules=[sys.modules[__name__]])
    tasks = set()  # avoid task to be garbage collected

    async def task_gen():
        while True:
            task = asyncio.create_task(background_job())
            tasks.add(task)
            task.add_done_callback(tasks.discard)
            await asyncio.sleep(10)

    tasks.add(asyncio.create_task(task_gen()))

    while True:
        await asyncio.sleep(60)
        logging.info("main loop: len(tasks) = %d", len(tasks))


if __name__ == "__main__":
    asyncio.run(main())
